/** 添加样式
 * @param id 唯一id
 * @param stylesheet 样式内容
 * @example appendStyle('my-style', 'body{background: #fff;}')
 */
export function appendStyle(id: string, stylesheet: string) {
  if (!(document.head.querySelector('style')?.id === id)) {
    const style = document.createElement('style');
    style.id = id;
    style.innerHTML = stylesheet;
    document.head.appendChild(style);
  }
}

/** 复制内容到剪贴板
 * @param msg 复制的内容
 * @example copyText('hello world')
 */
export function copyText(msg: string) {
  var textareaC = document.createElement('textarea');
  textareaC.setAttribute('readonly', 'readonly');   // 设置只读属性防止手机上弹出软键盘
  textareaC.value = msg;
  document.body.appendChild(textareaC);             // 将textarea添加为body子元素
  textareaC.select();
  document.execCommand('copy');
  document.body.removeChild(textareaC);             // 移除DOM元素
}

/** 获取url参数
 * @param key 参数名
 * @returns 参数值
 * @example
 * url: http://127.0.0.1:8000?key=app
 * const key = getUrlParmeter('key') // 'app'
 */
export function GetUrlQuery(key: string) {
  const urlSearch = new URLSearchParams(window.location.search);
  return urlSearch.get(key);
}

/** 文件转base64
 * @param file 文件对象
 * @example file2Base64(file).then(res => console.log(res))
 */
export const file2Base64 = (file: File): Promise<string> => new Promise(resolve => {
  const fd = new FileReader()
  fd.readAsDataURL(file)

  fd.onload = () => resolve(String(fd.result))
})

/** 加载图片
 * @param url 图片地址
 * @returns 图片对象
 * @example const img = loadImg('https://xx.com/xx.png') // 返回HTMLImageElement
 */
export function loadImg(url: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = url
    img.onload = () => resolve(img)
    img.onerror = reject
  })
}
/** 延迟执行
 * @param delay 延迟时间
 * @example
 * await delay(1000)
 * console.log('1s后执行')
 */
export const sleep = (delay = 500) => new Promise(resolve => setTimeout(resolve, delay));
/** 全屏展示或退出全屏 */
export const triggerFullScreen = (elm: Element = document.body) => {
  if (document.fullscreenEnabled) {
    if (document.fullscreenElement && document.fullscreenElement.nodeName) {
      document.exitFullscreen();
    } else elm.requestFullscreen();
  } else {
    console.log('你的浏览器不支持全屏模式！');
  }
}